package org.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.netty.handler.codec.serialization.ObjectEncoder;
import org.example.demo.entity.InspectionRecord;
import org.example.demo.entity.User;
import org.example.demo.service.InspectionRecordService;
import org.example.demo.service.UserService;
import org.example.demo.util.AjaxResult;
import org.example.demo.util.ReturnMap;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("inspection")
public class InspectionRecordController {

    @Resource
    private InspectionRecordService inspectionRecordService;

    @Resource
    private UserService userService;

    // 分页查询考察记录列表
    @PostMapping("selectPage")
    public AjaxResult selectPage(@RequestBody InspectionRecord record,
                                 @RequestParam(defaultValue = "1") Integer pageNum,
                                 @RequestParam(defaultValue = "10") Integer pageSize) {
        Map<String, Object> map = new HashMap<>();
//        ReturnMap returnMap = new ReturnMap();
        Page<InspectionRecord> page = new Page<>(pageNum, pageSize);

        // 收集所有用户
        Map<Long, User> userMap = userService.list(new QueryWrapper<User>().lambda().like(record.getNickName()!=null&&!record.getNickName().isEmpty(),User::getName,record.getNickName())).stream()
                .collect(Collectors.toMap(User::getId, user -> user));
        if (!userMap.isEmpty()) {
            // 批量查询用户信息
            QueryWrapper<InspectionRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().in(InspectionRecord::getUserId, userMap.keySet())
                    .orderByDesc(InspectionRecord ::getCreateTime);

            Page<InspectionRecord> result = inspectionRecordService.page(page, queryWrapper);
            // 遍历结果集，设置用户昵称
            for (InspectionRecord inspectionRecord : result.getRecords()) {
                User user = userMap.get(inspectionRecord.getUserId());
                if (user != null) {
                    inspectionRecord.setNickName(user.getName());
                }
            }
            map.put("page", result);
//            returnMap.setData("page", result);
        }else{
            map.put("page", new ArrayList<>());
//            returnMap.setData("page", new ArrayList<>());
        }

        return AjaxResult.success(map);
    }

    // 查询考察记录总数
    @PostMapping("selectCount")
    public AjaxResult selectCount(@RequestBody InspectionRecord record) {
//        ReturnMap returnMap = new ReturnMap();
        Map<String, Object> map = new HashMap<>();
        // 收集所有用户
        Map<Long, User> userMap = userService.list(new QueryWrapper<User>().lambda().like(record.getNickName()!=null&&!record.getNickName().isEmpty(),User::getName,record.getNickName())).stream()
                .collect(Collectors.toMap(User::getId, user -> user));
        if (!userMap.isEmpty()) {
            QueryWrapper<InspectionRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .in(InspectionRecord::getUserId, userMap.keySet())
                    .eq(record.getApplicantId() != null,
                            InspectionRecord::getApplicantId, record.getApplicantId());

            int count = inspectionRecordService.count(queryWrapper);
            map.put("count", count);
//            returnMap.setData("count", count);
        }else{
            map.put("count", 0);
//            returnMap.setData("count", 0);
        }

        return AjaxResult.success(map);
    }

    // 新增/修改考察记录
    @PostMapping("saveOrUpdate")
    public AjaxResult saveOrUpdate(@RequestBody InspectionRecord record) {
//        ReturnMap returnMap = new ReturnMap();
//        Map<String, Object> map = new HashMap<>();
        if (record.getId() != null) {
            record.setUpdateTime(LocalDateTime.now());
            inspectionRecordService.updateById(record);
        } else {
            record.setCreateTime(LocalDateTime.now());
            record.setUpdateTime(LocalDateTime.now());
            inspectionRecordService.save(record);
        }

//        returnMap.setReturnCode(200);
        return AjaxResult.success();
    }

    // 查询考察记录详情
    @GetMapping("selectById")
    public AjaxResult selectById(@RequestParam Integer id) {
//        ReturnMap returnMap = new ReturnMap();
        Map<String, Object> map = new HashMap<>();
        InspectionRecord record = inspectionRecordService.getById(id);
//        returnMap.setData("record", record);
        map.put("record", record);
        return AjaxResult.success(map);
    }

    // 删除考察记录
    @DeleteMapping("delete")
    public AjaxResult delete(@RequestParam Integer id) {
//        ReturnMap returnMap = new ReturnMap();
        Map<String, Object> map = new HashMap<>();
        boolean success = inspectionRecordService.removeById(id);
//        returnMap.setReturnCode(success ? 200 : 405);
        if (success) return AjaxResult.success();
        return AjaxResult.error();
//        return AjaxResult.success();
    }
}
